package com.indusfo.spc.service.impl;

import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.Device;
import com.indusfo.spc.pojo.Maintain;
import com.indusfo.spc.pojo.MaintainWork;
import com.indusfo.spc.pojo.MaintainWorkDetail;
import com.indusfo.spc.service.MaintainWorkService;
import com.indusfo.spc.untlis.DateUtils;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName MaintainWorkServiceImpl
 * @Description
 * @Author louk
 * @Date 2019/12/12 19:46
 */
@Service
public class MaintainWorkServiceImpl implements MaintainWorkService {
    @Resource
    MaintainWorkMapper maintainWorkMapper;
    @Resource
    MaintainWorkDetailMapper maintainWorkDetailMapper;
    @Resource
    MaintainMapper maintainMapper;
    /**
     * 新增设备保养计划
     * @param maintainWork
     * @return
     */
    @Override
    @Transactional
    public JSONObject insertMaintainWork(MaintainWork maintainWork, Integer[] maintainIds,Integer[] qualifiedIds) {
        maintainWork.setAuditState(1);
        String checkResult = checkParam(maintainWork);
        if(!StringUtils.isEmpty(checkResult)){
            return JSONObject.build(JSONObject.ERROR,checkResult);
        }
        int insertCount = maintainWorkMapper.insertMaintainWork(maintainWork);
        if(insertCount>0){
            /**
             * 当新增成功一个设备保养计划默认
             * 将其所属的设备的设备类型的设备保养项目,
             * 设备保养计划单下的保养项目
             * 都添加到设备保养作业明细表里
             */
            //设备id
//            Integer deviceId = maintainWork.getDeviceId();
            //获取到该设备类型下的保养项目id集合
//            List<Integer> inspectIdList=deviceTypeMaintainMapper.queryByDeviceId(deviceId);
            //获取设备保养计划单下的保养项目id
            /*List<Integer> maintainIdList = maintainPlanDetailMapper.queryByMaintainPlan(maintainWork.getMaintainPlanId());
            if(maintainIds!=null && maintainIds.length!=0){
                if(!maintainIdList.isEmpty()){
                    for (Integer maintainId : maintainIds) {
                        maintainIdList.add(maintainId);
                    }
                }else{
                    int updateCount = maintainWorkDetailMapper.updateMaintainWorkDetailList(maintainWork.getMaintainWorkId(), maintainIds);
                    if(updateCount>0){
                        return JSONObject.build(JSONObject.SUCCESS,"新增成功");
                    }
                }
                return JSONObject.build(JSONObject.ERROR,"新增设备保养明细失败");
            }
            if(!maintainIdList.isEmpty()){
                Integer[] inspectIdArray=new Integer[maintainIdList.size()];
                Integer[] newInspectIdArray = maintainIdList.toArray(inspectIdArray);
                int updateCount = maintainWorkDetailMapper.updateMaintainWorkDetailList(maintainWork.getMaintainWorkId(), newInspectIdArray);
            }*/
            boolean judgeFlag1=false;
            boolean judgeFlag2=false;
            boolean judgeFlag3=false;
            if(maintainIds==null && qualifiedIds!=null){
                judgeFlag1=true;
            }
            if(maintainIds!=null && qualifiedIds==null){
                judgeFlag2=true;
            }
            if(maintainIds!=null && qualifiedIds!=null && maintainIds.length!=qualifiedIds.length){
                judgeFlag3=true;
            }
            //判断两个数组是否长度一样
            if( judgeFlag1 || judgeFlag2 || judgeFlag3 ){
                return JSONObject.build(JSONObject.ERROR,"保养明细与状态信息不匹配");
            }else if(maintainIds!=null && maintainIds.length>0){
                List<MaintainWorkDetail> maintainWorkDetailList=new ArrayList<>();
                for (int i = 0; i < maintainIds.length; i++) {
                    MaintainWorkDetail maintainWorkDetail=new MaintainWorkDetail(maintainIds[i],maintainWork.getMaintainWorkId(),qualifiedIds[i]);
                    maintainWorkDetailList.add(maintainWorkDetail);
                }
                //直接对传递过来的数组进行新增到明细中
                int insertMatinWorkDetailList = maintainWorkDetailMapper.insertMatinWorkDetailList(maintainWorkDetailList);
            }
            return JSONObject.build(JSONObject.SUCCESS,"新增成功");
        }
        return JSONObject.build(JSONObject.ERROR,"新增失败");
    }
    /**
     * 查询设备保养作业明细
     * @param maintainWorkDetail
     * @return
     */
    @Override
    public JSONObject queryMaintainWorkDetail(MaintainWorkDetail maintainWorkDetail) {
        Integer pagesize = maintainWorkDetail.getPagesize();
        Integer pageindex = maintainWorkDetail.getPageindex();
        if(pagesize != null && pageindex != null) {
            maintainWorkDetail.setIncept(pagesize*(pageindex - 1));
        }
        List<MaintainWorkDetail> maintainPlanDetailList = maintainWorkDetailMapper.queryMaintainWorkDetail(maintainWorkDetail);
        if(!maintainPlanDetailList.isEmpty()){
            int count = maintainWorkDetailMapper.countMaintainWorkDetail(maintainWorkDetail);
            return JSONObject.oK(maintainPlanDetailList,count);
        }
        return JSONObject.oK(maintainPlanDetailList,null);
    }
    /**
     * 编辑设备保养作业
     * @param maintainWork
     * @return
     */
    @Override
    public JSONObject updateMaintainWorkTain(MaintainWork maintainWork, Integer[] maintainIds,Integer[] qualifiedIds) {
        Boolean flag=false;
        if (maintainWork.getMaintainWorkId()==null || "".equals(maintainWork.getMaintainWorkId())){
            return JSONObject.build(JSONObject.ERROR,"请选择设备保养计划");
        }
        String checkResult = checkParam(maintainWork);
        if(!StringUtils.isEmpty(checkResult)){
            return JSONObject.build(JSONObject.ERROR,checkResult);
        }
        if(maintainWork.getAuditState()!=null &&  maintainWork.getAuditState()==2){
            return JSONObject.build(JSONObject.ERROR,"审核过的不能编辑");
        }
        Map<Integer,MaintainWorkDetail> maintainWorkDetailMap=new HashMap<>();
        boolean judgeFlag1=false;
        boolean judgeFlag2=false;
        boolean judgeFlag3=false;
        if(maintainIds==null && qualifiedIds!=null){
            judgeFlag1=true;
        }
        if(maintainIds!=null && qualifiedIds==null){
            judgeFlag2=true;
        }
        if(maintainIds!=null && qualifiedIds!=null && maintainIds.length!=qualifiedIds.length){
            judgeFlag3=true;
        }
        //判断两个数组是否长度一样
        if( judgeFlag1 || judgeFlag2 || judgeFlag3 ){
            return JSONObject.build(JSONObject.ERROR,"保养明细与状态信息不匹配");
        }else {
            for (int i = 0; i < maintainIds.length; i++) {
                MaintainWorkDetail maintainWorkDetail=new MaintainWorkDetail(maintainIds[i],maintainWork.getMaintainWorkId(),qualifiedIds[i]);
                maintainWorkDetailMap.put(maintainIds[i],maintainWorkDetail);
            }
            //获取当前设备保养作业下的所有明细的保养项目id
            List<Integer> queryMaintainIdList = maintainWorkDetailMapper.queryMaintainIdList(maintainWork);
            List<MaintainWorkDetail> insertList=new ArrayList<>();
            List<MaintainWorkDetail> deleteList=new ArrayList<>();
            List<MaintainWorkDetail> updateList=new ArrayList<>();
            //所传递的数组当中不存在数据库查询的集合说明删除了,数据库查询的集合中不存在传递的数组说明是新增
            if(!maintainWorkDetailMap.isEmpty() && !queryMaintainIdList.isEmpty()){
                for (int i = 0; i < maintainIds.length; i++) {
                    MaintainWorkDetail maintainWorkDetail=new MaintainWorkDetail(maintainIds[i],maintainWork.getMaintainWorkId(),qualifiedIds[i]);
                    maintainWorkDetailMap.put(maintainIds[i],maintainWorkDetail);
                }
                for (Integer maintainId : maintainIds) {
                    //不包含说明是要进行新增的
                    if(!queryMaintainIdList.contains(maintainId)){
                        insertList.add(maintainWorkDetailMap.get(maintainId));
                    }
                }
                for (Integer maintainId : queryMaintainIdList) {
                    if(!maintainWorkDetailMap.containsKey(maintainId)){
                        MaintainWorkDetail maintainWorkDetail = new MaintainWorkDetail();
                        maintainWorkDetail.setMaintainWorkId(maintainWork.getMaintainWorkId());
                        maintainWorkDetail.setMaintainId(maintainId);
                        deleteList.add(maintainWorkDetail);
                    }else{
                        updateList.add(maintainWorkDetailMap.get(maintainId));
                    }
                }
                if(!insertList.isEmpty()){
                    maintainWorkDetailMapper.insertMatinWorkDetailList(insertList);
                }
                if(!deleteList.isEmpty()){
                    maintainWorkDetailMapper.defineMatinWorkDetailList(deleteList,2);
                }
                if(!updateList.isEmpty()){
                    maintainWorkDetailMapper.updateMatinWorkDetailList(updateList);
                }
            }else if(maintainWorkDetailMap.isEmpty() && !queryMaintainIdList.isEmpty()){
                //如果传递的明细数据为空,而数据库数据存在明细数据则说明删除删除数据库中的数据
                maintainWorkDetailMapper.defineMaintainPlanDetail(maintainWork.getMaintainWorkId(),queryMaintainIdList.toArray(new Integer[queryMaintainIdList.size()]),2);
            }else if(!maintainWorkDetailMap.isEmpty() && queryMaintainIdList.isEmpty()){
                //如果传递的数据不为空,而数据库不存在数据则只进行新增
                for (Integer maintainId : maintainWorkDetailMap.keySet()) {
                    insertList.add(maintainWorkDetailMap.get(maintainId));
                }
                maintainWorkDetailMapper.insertMatinWorkDetailList(insertList);
            }
            int updateCount=maintainWorkMapper.updateMaintainWork(maintainWork);
            if(updateCount>0){
                return JSONObject.build(JSONObject.SUCCESS,"编辑成功");
            }
            return JSONObject.build(JSONObject.ERROR,"编辑失败");
        }

    }
    /**
     * 审核状态修改
     * @param maintainWorkIds
     * @param auditState
     * @return
     */
    @Override
    @Transactional
    public JSONObject auditStateChange(Integer[] maintainWorkIds, Integer auditState,Integer[] auditStateIds) {
        if(maintainWorkIds==null || "".equals(maintainWorkIds)){
            return JSONObject.build(JSONObject.ERROR,"请选择设备保养作业单号");
        }
        if(auditState==null || "".equals(auditState)){
            return JSONObject.build(JSONObject.ERROR,"审核状态未传递");
        }
        if(auditStateIds==null || auditStateIds.length==0 ){
            return JSONObject.build(JSONObject.ERROR,"未获取到当前信息的审核状态");
        }
        for (Integer auditStateId : auditStateIds) {
            if(auditState==auditStateId){
                if(auditState==1){
                    return JSONObject.build(JSONObject.ERROR,"未审核的不能反审核");
                }else if(auditState==2){
                    return JSONObject.build(JSONObject.ERROR,"已审核,不能再审核");
                }
            }
        }
        int auditStateChangeCount = maintainWorkMapper.auditStateChange(maintainWorkIds, auditState);
        if(auditStateChangeCount>0){
            //如果是对审核状态进行修改,那么更新设备信息的保养时间
            //已审核进行时间的更新
            if(auditState==2){
                List<Device> deviceList = maintainWorkMapper.queryMaintainPeriod(maintainWorkIds);
                if(!deviceList.isEmpty()){
                    for (Device device : deviceList) {
                        Integer maintainPeriod = device.getMaintainPeriod();
                        String maintainWorkDate = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date());
                        String simpleDate = DateUtils.getSimpleDate(maintainWorkDate, maintainPeriod);
                        device.setMaintainDate(maintainWorkDate);
                        device.setNmaintainDate(simpleDate);
                    }
                    maintainWorkMapper.updateDevice(deviceList);
                }
            }
            return JSONObject.build(JSONObject.SUCCESS,"审核状态修改成功");
        }
        return JSONObject.build(JSONObject.ERROR,"审核状态修改失败");
    }
    /**
     * 查询设备保养作业
     * @param maintainWork
     * @return
     */
    @Override
    public JSONObject queryMaintainWork(MaintainWork maintainWork,String startDate,String endDate) {
        Integer pagesize = maintainWork.getPagesize();
        Integer pageindex = maintainWork.getPageindex();
        if(pagesize != null && pageindex != null) {
            maintainWork.setIncept(pagesize*(pageindex - 1));
        }
        if(!StringUtils.isEmpty(startDate)){
            try {
                Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startDate);
            } catch (ParseException e) {
                return JSONObject.build(JSONObject.ERROR,"开始日期格式错误");
            }
        }
        if(!StringUtils.isEmpty(endDate)){
            try {
                Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDate);
            } catch (ParseException e) {
                return JSONObject.build(JSONObject.ERROR,"结束日期格式错误");
            }
        }
        List<MaintainWork> maintainPlanList = maintainWorkMapper.queryMaintainWorkList(maintainWork,startDate,endDate);
        if(!maintainPlanList.isEmpty()){
            int count = maintainWorkMapper.countMaintainWorkList(maintainWork,startDate,endDate);
            return JSONObject.oK("查询成功",maintainPlanList,count);
        }
        return JSONObject.oK("没有相关数据",maintainPlanList,null);
    }
    /**
     * 数据状态修改
     * @param maintainWorkIds
     * @param dataState
     * @return
     */
    @Override
    @Transactional
    public JSONObject defineDataState(Integer[] maintainWorkIds,Integer dataState,Integer[] auditState){
        if(maintainWorkIds==null || maintainWorkIds.length==0  ){
            return JSONObject.build(JSONObject.ERROR,"请选择设备保养作业单号");
        }
        if(dataState==null || "".equals(dataState)){
            return JSONObject.build(JSONObject.ERROR,"未传递数据状态");
        }
        if(auditState==null || auditState.length==0){
            return JSONObject.build(JSONObject.ERROR,"未获取到当前审核状态");
        }
        for (Integer as : auditState) {
            if(as==2){
                return JSONObject.build(JSONObject.ERROR,"已审核的无法删除");
            }
        }
        int defineCount = maintainWorkMapper.defineDataState(maintainWorkIds, dataState);
        maintainWorkDetailMapper.defineByMaintainWorkId(maintainWorkIds,dataState);
        if(defineCount>0){
            return JSONObject.build(JSONObject.SUCCESS,"删除成功");
        }
        return JSONObject.build(JSONObject.SUCCESS,"删除失败");
    }

    @Override
    public JSONObject filterMaintainList(MaintainWork maintainWork,Integer[] maintainIds){
        Integer pagesize = maintainWork.getPagesize();
        Integer pageindex = maintainWork.getPageindex();
        Integer incept=null;
        if(pagesize != null && pageindex != null) {
            maintainWork.setIncept(pagesize*(pageindex - 1));
            incept=pagesize*(pageindex - 1);
        }
        List<Maintain> maintainList = maintainMapper.filterMaintainListByMaintainIds(pagesize,incept,maintainIds);
        if(!maintainList.isEmpty()){
            int  count = maintainMapper.countFilterMaintainListByMaintainIds(maintainIds);
            return JSONObject.oK("查询成功",maintainList,count);
        }
        return JSONObject.oK("没有相关数据",maintainList,null);
    }

    @Override
    public JSONObject queryMaintainByMaintainWork(MaintainWork maintainWork) {
        //设备保养计划id
        Integer maintainPlanId = maintainWork.getMaintainPlanId();
        //设备id
        Integer deviceId = maintainWork.getDeviceId();
        List<Maintain> maintainList = maintainMapper.queryByMaintainWork(maintainWork);
        if(!maintainList.isEmpty()){
            return JSONObject.oK("查询成功",maintainList,maintainList.size());
        }
        return JSONObject.oK("没有相关数据",maintainList,maintainList.size());
    }

    public String checkParam(MaintainWork maintainWork){
        //设备保养作业编号
        String maintainWorkNo = maintainWork.getMaintainWorkNo();
        //设备id
        Integer deviceId = maintainWork.getDeviceId();
        //设备保养计划单号
//        Integer maintainPlanId = maintainWork.getMaintainPlanId();
        //审核状态id
        Integer auditState = maintainWork.getAuditState();
        //用户id
        Integer userId = maintainWork.getUserId();
        //备注
        String remark = maintainWork.getRemark();
        /*if(maintainPlanId==null || "".equals(maintainPlanId)){
            return "未选择设备保养计划单号";
        }*/
        if(deviceId==null || "".equals(deviceId)){
            return "未选择设备";
        }
        if(auditState==null || "".equals(auditState)){
            return "未选择审核状态";
        }
        if(userId==null || "".equals(userId)){
            return "制单人未传递";
        }
        if(StringUtils.isEmpty(maintainWorkNo)){
            return "设备保养编号为空";
        }
        if(!StringUtils.isEmpty(remark) && remark.getBytes().length>100){
            return "备注内容过长,长度为100";
        }
        int noCount = maintainWorkMapper.queryWorkNo(maintainWork);
        if(noCount>0){
            return "设备保养作业编号已存在";
        }
        return null;
    }
}
